package com.loren.demo03.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class HttpSocketServer {

    private static final int HTTP_PORT = 8080;

    public static void main(String[] args) {
        EventLoopGroup parentGroup = new NioEventLoopGroup(1);
        EventLoopGroup childGroup = new NioEventLoopGroup(2);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new HttpSocketServerInitializer());

            // 启动服务器并绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(HTTP_PORT).sync();

            channelFuture.addListener(future -> {
                if (future.isSuccess()) {
                    System.out.println("HTTP Server listening port is " + HTTP_PORT);
                } else {
                    System.err.println("HTTP Server listening port failed");
                }
            });

            // 对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            childGroup.shutdownGracefully();
            parentGroup.shutdownGracefully();
        }
    }
}
